<?php

/**
 * PaymentController is the default controller for this application
 */
class PaymentController extends BrowseControllerBase {
	/*
	 * PackageOptionDataService
	 */
	public $dealOptionDataService = null;
	
	/**
	 *
	 * PackageOrderDataService
	 * @var PackageOrderDataService Object
	 */
	public $dealOrderDataService = null;
	
	/**
	 *
	 * UsersDataService Object
	 * @var UsersDataService object
	 */
	public $usersDataService = null;
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		//Check if User is logged in
		$currentUserId = $this->authentication->getCurrentUserId ();
		if ($currentUserId == null) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		// Init all Data Service
		$this->usersDataService = new UsersDataService ();
		
		// Check if user has verified payment or expired here
		$currentUser = $this->usersDataService->getById ( $currentUserId );
		if (! empty ( $currentUser ) && $currentUser->userType != "MEMBER") {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		$this->dealOptionDataService = new PackageOptionsDataService ();
		$this->dealOrderDataService = new PackageOrderDataService ();
		
		// Load Payment Configuration
		$this->loadAllPayment ();
	}
	
	public function indexAction() {
		$usersDataService = new UsersDataService ();
		$currentUser = $usersDataService->getById ( $this->authentication->getCurrentUserId () );
		
		if ($currentUser == null) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		//Check expired
		$user_id = $this->authentication->getCurrentUserId ();
		$dealOptionId = $currentUser->dealOptionId;
		$isExpired = $this->dealOrderDataService->isExpired ( $user_id, $dealOptionId );
		if ($isExpired) {
			
			$this->smarty->assign ( 'message', "Your Package is expired. Please renew it via below form." );
		} else {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/MyAccount/index';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		// Get CurrentPackagePrice
		$currentPackage = $this->dealOptionDataService->getById ( $currentUser->dealOptionId );
		$this->smarty->assign ( 'price', $currentPackage->price );
		
		// Get List of Package
		$arrElement = array ();
		$listPackages = $this->dealOptionDataService->getItems ( $arrElement );
		// Get Brand Free Attribute
		$this->smarty->assign ( 'brandFree', $currentUser->brandFree );
		$this->smarty->assign ( 'listPackages', $listPackages );
		
		$this->smarty->assign ( 'id', $currentUser->dealOptionId );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Payment/payment.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Process Payment for Signup
	 */
	public function processpaymentAction() {
		
		$userId = $this->authentication->getCurrentUserId ();
		$dealOptionId = $this->getPost ( 'dealOptionId', '' );
		$dealEntity = $this->dealOptionDataService->getById ( $dealOptionId );
		
		if (empty ( $dealEntity )) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		$amount = $dealEntity->price;
		$paymentMethod = $this->getPost ( 'paymentMethod', '' );
		$brandFree = $this->getPost ( 'brandFree', '0' );
		
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		if (! empty ( $amount ) && floatval ( $amount ) > 0 && $actionForm != "cancel") {
			
			if ($paymentMethod == PAYMENT_PAYPAL) {
				//Check if exist previous Package, then cancel it before create a new one
				// Check if this user is verified.
				$arrElement = array ();
				$arrElement ['userId'] = $this->authentication->getCurrentUserId ();
				$arrElement ['paymentMethod'] = PAYMENT_PAYPAL;
				$arrElement ['status'] = PackageOrderEntity::COMPLETED;
				$items = $this->dealOrderDataService->getItems ( $arrElement, " createdDate DESC " );
				if (count ( $items ) > 0) {
					$item = $items [0];
					// Get ProfileId
					$profileId = $item->profileId;
					try {
						$paypalConfig = $this->settingsDataService->getPaypalSettings ();
						$paypalGateway = new PayPalGateway ( $paypalConfig );
						$paypalGateway->setConfig ( $paypalConfig );
						
						$paypalGateway->cancelSubscription ( $profileId, "User Cancel the recurring payment" );
						
						$item->profileId = "";
						$item->status = PackageOrderEntity::CANCELLED;
						$this->dealOrderDataService->update ( $item );
					} catch ( Exception $ex ) {
						//echo $ex->getMessage();
					//die();
					}
				
				}
				
				// Save to deposit table
				$dealOrderEntity = $this->dealOrderDataService->beforeCreate ();
				$dealOrderEntity->cost = round ( $amount, 2 );
				$dealOrderEntity->userId = $userId;
				if ($brandFree == "1") {
					$dealOrderEntity->brandFee = 5;
					$amount = round ( $amount, 2 ) + 5;
					$dealOrderEntity->totalFee = $amount;
				} else {
					$dealOrderEntity->brandFee = 0;
					$dealOrderEntity->totalFee = $amount;
				}
				
				// Assign PaymentMethod
				$dealOrderEntity->paymentMethod = PAYMENT_PAYPAL;
				$dealOrderEntity->note = 'Payment:' . date ( 'Y-m-d H:i:s' );
				$dealOrderEntity->currency = 'GBP';
				$dealOrderEntity->dealOptionId = $dealOptionId;
				$dealOrderEntity->createdDate = date ( 'Y-m-d H:i:s' );
				$today = date ( 'Y-m-d' );
				$expiredDate = date ( 'Y-m-d', strtotime ( "$today + 1 months" ) );
				$dealOrderEntity->expiredDate = $expiredDate;
				$dealOrderEntity->status = PackageOrderEntity::PENDING;
				$id = $this->dealOrderDataService->create ( $dealOrderEntity );
				
				if (empty ( $id )) {
					$this->indexAction ();
					return;
				}
				
				try {
					$params ['return_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Payment&action=returnPayment' . '&state=return&order_id=' . $id;
					$params ['cancel_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Payment&action=returnPayment' . '&state=cancel&order_id=' . $id;
					$params ['ipn_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=PaypalIpn&action=index&order_id=' . $id;
					
					$paypalConfig = $this->settingsDataService->getPaypalSettings ();
					$paypalGateway = new PayPalGateway ( $paypalConfig );
					$paypalGateway->setConfig ( $paypalConfig );
					// Get GateWay URL
					$transactionUrl = $paypalGateway->getGatewayUrl ();
					$transaction = $paypalGateway->createSubscriptionTransaction ( $dealOrderEntity, $params );
					
					$transactionData = $transaction->getData ();
					// Handle redirection
					$transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData ['token'];
					
					$dealOrderEntity = $this->dealOrderDataService->beforeUpdate ( $id );
					$dealOrderEntity->token = urldecode ( $transactionData ['token'] );
					$dealOrderEntity->status = PackageOrderEntity::PROCESSING;
					$this->dealOrderDataService->update ( $dealOrderEntity );
					
					header ( "Location: " . $transactionUrl );
				} catch ( ExceptionAbstract $ex ) {
				}
			} else if ($paymentMethod == PAYMENT_2CHECKOUT) {
				
				// Check if there's product
				// Save to deposit table
				$dealOrderEntity = $this->dealOrderDataService->beforeCreate ();
				$dealOrderEntity->cost = round ( $amount, 2 );
				$dealOrderEntity->userId = $userId;
				if ($brandFree == "1") {
					$dealOrderEntity->brandFee = 5;
					$amount = round ( $amount, 2 ) + 5;
					$dealOrderEntity->totalFee = $amount;
				} else {
					$dealOrderEntity->brandFee = 0;
				}
				
				// Assign PaymentMethod
				$dealOrderEntity->paymentMethod = PAYMENT_2CHECKOUT;
				$dealOrderEntity->note = 'Payment:' . date ( 'Y-m-d H:i:s' );
				$dealOrderEntity->currency = 'GBP';
				$dealOrderEntity->dealOptionId = $dealOptionId;
				$dealOrderEntity->createdDate = date ( 'Y-m-d H:i:s' );
				$today = date ( 'Y-m-d' );
				$expiredDate = date ( 'Y-m-d', strtotime ( "$today + 1 months" ) );
				$dealOrderEntity->expiredDate = $expiredDate;
				$dealOrderEntity->status = PackageOrderEntity::PENDING;
				$id = $this->dealOrderDataService->create ( $dealOrderEntity );
				
				if (empty ( $id )) {
					$this->indexAction ();
					return;
				}
				try {
					$params ['return_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Payment&action=returnPayment2' . '&state=return&order_id=' . $id;
					$params ['cancel_url'] = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/index.php?authen=Browse&control=Payment&action=returnPayment2' . '&state=cancel&order_id=' . $id;
					$params ['merchant_order_id'] = $id;
					
					$checkoutConfig = $this->settingsDataService->get2CheckoutSettings ();
					unset ( $checkoutConfig ['vendor_id'] );
					$checkoutGateway = new TwoCheckoutGateway ( $checkoutConfig );
					$checkoutGateway->setConfig ( $checkoutConfig );
					// Get GateWay URL
					$transactionUrl = $checkoutGateway->getGatewayUrl ();
					$transaction = $checkoutGateway->createSubscriptionTransaction ( $dealOrderEntity, $params );
					
					$transactionData = $transaction->getData ();
					$transactionUrl = $checkoutGateway->getGatewayUrl ();
					$transactionMethod = $checkoutGateway->getGatewayMethod ();
					
					$dealOrderEntity = $this->dealOrderDataService->beforeUpdate ( $id );
					$dealOrderEntity->token = NULL;
					$dealOrderEntity->status = PackageOrderEntity::PROCESSING;
					$this->dealOrderDataService->update ( $dealOrderEntity );
					$transactionUrl .= '?' . http_build_query ( $transactionData );
					header ( "Location: " . $transactionUrl );
				} catch ( ExceptionAbstract $ex ) {
					// We will add Log here
					echo $ex->getMessage ();
				
		//die();
				}
			}
		} else if ($actionForm == "cancel") {
		
		}
	}
	
	/**
	 * Handle Return Pay from Paypal
	 */
	public function returnPaymentAction() {
		$paypalConfig = $this->settingsDataService->getPaypalSettings ();
		$paypalGateway = new PayPalGateway ( $paypalConfig );
		$paypalGateway->setConfig ( $paypalConfig );
		
		$token = $_GET ['token'];
		$dealOrderEntity = $this->dealOrderDataService->getByToken ( $token );
		
		if (is_null ( $dealOrderEntity )) {
			$this->indexAction ();
			return;
		}
		
		try {
			$result = $paypalGateway->onSubscriptionTransactionReturn ( $dealOrderEntity, $_GET );
			if ($result == SUCC) {
				$dealOrderEntity->status = PackageOrderEntity::COMPLETED;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				
				//Hold tp update User status
				$usersDataService = new UsersDataService ();
				$currentUser = $usersDataService->getById ( $dealOrderEntity->userId );
				
				if ($currentUser) {
					$currentUser->hasVerified = 1;
					$currentUser->paymentMethod = PAYMENT_PAYPAL;
					$currentUser->dealOptionId = $dealOrderEntity->dealOptionId;
					$usersDataService->update ( $currentUser );
				}
				
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/completed';
				CommonUtils::redirect ( $url );
				return;
			} else {
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/cancel';
				CommonUtils::redirect ( $url );
				return;
			}
		} catch ( ExceptionAbstract $ex ) {
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/cancel';
			CommonUtils::redirect ( $url );
			return;
		
		//echo $ex->getMessage();
		}
	
	}
	
	public function returnPayment2Action() {
		$config = $this->settingsDataService->get2CheckoutSettings ();
		unset ( $config ['vendor_id'] );
		$checkoutGateway = new TwoCheckoutGateway ( $config );
		$checkoutGateway->setConfig ( $config );
		
		$order_id = isset ( $_POST ['order_id'] ) ? $_POST ['order_id'] : "";
		if (empty ( $order_id )) {
			$order_id = isset ( $_GET ['order_id'] ) ? $_GET ['order_id'] : "";
		}
		$dealOrderEntity = $this->dealOrderDataService->getById ( $order_id );
		if (is_null ( $dealOrderEntity )) {
			$this->indexAction ();
			return;
		}
		
		try {
			// Print Details sale
			//$sale_id = $_POST['order_number'];
			//$invoice_id = $_POST['invoice_id'];
			//echo $sale_id;
			//echo $invoice_id;
			//$listSales = $checkoutGateway->getService()->listSales();
			//echo "<pre>" . print_r($listSales, true) . "</pre>";
			//$sale = $checkoutGateway->getService()->detailSale($sale_id, $invoice_id);
			

			//$lineItemId = $sale['lineitem_id'];
			//$respondData = $checkoutGateway->getService()->stopLineItemRecurring($lineItemId);
			//echo "<pre>" . print_r($respondData, true) . "</pre>";
			//die();
			

			$result = $checkoutGateway->onSubscriptionTransactionReturn ( $dealOrderEntity, $this->getPost () );
			if ($result == SUCC) {
				
				$dealOrderEntity->status = PackageOrderEntity::COMPLETED;
				$this->dealOrderDataService->update ( $dealOrderEntity );
				
				//Hold tp update User status
				$usersDataService = new UsersDataService ();
				$currentUser = $usersDataService->getById ( $dealOrderEntity->userId );
				
				if ($currentUser) {
					$currentUser->hasVerified = 1;
					$currentUser->dealOptionId = $dealOrderEntity->dealOptionId;
					$currentUser->paymentMethod = PAYMENT_2CHECKOUT;
					$usersDataService->update ( $currentUser );
				}
				
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/completed';
				CommonUtils::redirect ( $url );
				return;
			} else {
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/cancel';
				CommonUtils::redirect ( $url );
				return;
			}
		} catch ( ExceptionAbstract $ex ) {
			echo $ex->getMessage ();
			//die();
			

			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/cancel';
			CommonUtils::redirect ( $url );
			return;
		
		//echo $ex->getMessage();
		}
	
		//die();
	

	}
	
	/**
	 * Handle when Paypal callback
	 */
	public function paymentcompleteAction() {
		$nvpComponent = new PaypalNvpComponent ();
		$token = $_GET ['token'];
		// GetExpressCheckoutDetails to get PAYERID
		$result = $nvpComponent->getExpressCheckoutDetails ( array ('token' => $token ) );
		
		$dealOrderEntity = $this->dealOrderDataService->getByToken ( $token );
		
		if (is_null ( $dealOrderEntity )) {
			$this->indexAction ();
			return;
		}
		
		/*
		 if( $nvpComponent->isSuccess($result) ) {
			// Call doExpressCheckoutPayment to perform payment
			$result2 = $nvpComponent->doExpressCheckoutPayment(array(
			'token' 	=> $token,
			'action'	=> PaypalNvpComponent::PAYPAL_ORDER_TYPE_SALE,
			'payerId' 	=> $result['PAYERID'],
			'amount' 	=> $dealOrderEntity->cost,
			'currencyID' => 'GBP'
			));

			if( $nvpComponent->isSuccess($result2) ) {
			$this->dealOrderDataService->updateStatus($dealOrderEntity->id, dealOrderEntity::COMPLETED);
			$usersDataService = new UsersDataService();
			$currentUser = $usersDataService->getById($dealOrderEntity->userId);

			if($currentUser)
			{
			$currentUser->hasVerified = 1;
			$currentUser->dealOptionId = $dealOrderEntity->dealOptionId;
			$usersDataService->update($currentUser);
			}

			} else {
			$this->indexAction();
			return;
			}

			} else {
			//print_r($result);
			$this->indexAction();
			return;
			}
			*/
		
		// Redirect to complete page
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/Payment/completed';
		CommonUtils::redirect ( $url );
		return;
	}
	
	public function completedAction() {
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Payment/payment_complete.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Cancel Payment Handling
	 */
	public function cancelAction() {
		$currentUser = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
		if ($currentUser) {
			if ($currentUser->hasVerified == 0) {
				// Do not pay money
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse';
				CommonUtils::redirect ( $url );
				return;
			}
		} else {
			// Do not pay money
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse';
			CommonUtils::redirect ( $url );
			return;
		}
		
		//Get Payment Method
		$paymentMethod = $currentUser->paymentMethod;
		
		if ($paymentMethod == PAYMENT_PAYPAL) {
			
			// Check if this user is verified.
			$arrElement = array ();
			$arrElement ['userId'] = $this->authentication->getCurrentUserId ();
			$arrElement ['paymentMethod'] = PAYMENT_PAYPAL;
			$arrElement ['status'] = PackageOrderEntity::COMPLETED;
			$items = $this->dealOrderDataService->getItems ( $arrElement, " createdDate DESC " );
			if (count ( $items ) > 0) {
				$item = $items [0];
				// Get ProfileId
				$profileId = $item->profileId;
				try {
					$paypalConfig = $this->settingsDataService->getPaypalSettings ();
					$paypalGateway = new PayPalGateway ( $paypalConfig );
					$paypalGateway->setConfig ( $paypalConfig );
					
					$paypalGateway->cancelSubscription ( $profileId, "User Cancel the recurring payment" );
					
					$item->profileId = "";
					$item->status = PackageOrderEntity::CANCELLED;
					$this->dealOrderDataService->update ( $item );
				} catch ( Exception $ex ) {
					//echo $ex->getMessage();
				//die();
				}
			
			}
			
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse';
			CommonUtils::redirect ( $url );
			return;
		
		} else if ($paymentMethod == PAYMENT_2CHECKOUT) {
			$arrElement = array ();
			$arrElement ['userId'] = $this->authentication->getCurrentUserId ();
			$arrElement ['paymentMethod'] = PAYMENT_2CHECKOUT;
			$arrElement ['status'] = PackageOrderEntity::COMPLETED;
			$items = $this->dealOrderDataService->getItems ( $arrElement, " createdDate DESC " );
			if (count ( $items ) > 0) {
				$item = $items [0];
				// Get ProfileId
				$profileId = $item->profileId;
				try {
					$checkoutConfig = $this->settingsDataService->getPaypalSettings ();
					unset ( $checkoutConfig ['vendor_id'] );
					$gateway = new TwoCheckoutGateway ( $checkoutConfig );
					$gateway->setConfig ( $checkoutConfig );
					
					//List Line_Item_id
					$sale_detail = $gateway->getService ()->detailSale ( $profileId );
					if (isset ( $sale_detail ['lineitem_id'] )) {
						$lineItem_id = $sale_detail ['lineitem_id'];
						
						$gateway->getService ()->stopLineItemRecurring ( $lineItem_id );
						
						$item->profileId = "";
						$item->status = PackageOrderEntity::CANCELLED;
						$this->dealOrderDataService->update ( $item );
					}
				} catch ( Exception $ex ) {
					//echo $ex->getMessage();
				//die();
				}
			
			}
			
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse';
			CommonUtils::redirect ( $url );
			return;
		}
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Payment/payment_cancel.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	public function upgradeAction() {
		$usersDataService = new UsersDataService ();
		$currentUser = $usersDataService->getById ( $this->authentication->getCurrentUserId () );
		
		if ($currentUser == null) {
			// Go on to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		//Check expired
		$user_id = $this->authentication->getCurrentUserId ();
		$dealOptionId = $currentUser->dealOptionId;
		$isExpired = $this->dealOrderDataService->isExpired ( $user_id, $dealOptionId );
		/*if($isExpired)
		 {

			$this->smarty->assign('message',"Your Package is expired. Please renew it via below form.");
			}
			else
			{
			// Go on to login page
			$url = Zend_Registry::get('config')->APPLICATION_URL . '/Browse/MyAccount/index';
			CommonUtils::redirect($url);
			return -1;
			}
			*/
		// Get CurrentPackagePrice
		$currentPackage = $this->dealOptionDataService->getById ( $currentUser->dealOptionId );
		$this->smarty->assign ( 'price', $currentPackage->price );
		
		// Get List of Package
		$arrElement = array ();
		$listPackages = $this->dealOptionDataService->getItems ( $arrElement );
		// Get Brand Free Attribute
		$this->smarty->assign ( 'brandFree', $currentUser->brandFree );
		$this->smarty->assign ( 'listPackages', $listPackages );
		
		$this->smarty->assign ( 'id', $currentUser->dealOptionId );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Payment/upgrade.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	public function acancelAction() {
		$currentUser = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
		if ($currentUser) {
			if ($currentUser->hasVerified == 0) {
				// Do not pay money
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse';
				CommonUtils::redirect ( $url );
				return;
			}
		} else {
			// Do not pay money
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse';
			CommonUtils::redirect ( $url );
			return;
		}
		//Get Payment Method
		$paymentMethod = $currentUser->paymentMethod;
		
		if ($paymentMethod == PAYMENT_PAYPAL) {
			
			// Check if this user is verified.
			$arrElement = array ();
			$arrElement ['userId'] = $this->authentication->getCurrentUserId ();
			$arrElement ['paymentMethod'] = PAYMENT_PAYPAL;
			$arrElement ['status'] = PackageOrderEntity::COMPLETED;
			$items = $this->dealOrderDataService->getItems ( $arrElement, " createdDate DESC " );
			if (count ( $items ) > 0) {
				$item = $items [0];
				// Get ProfileId
				$profileId = $item->profileId;
				try {
					$paypalConfig = $this->settingsDataService->getPaypalSettings ();
					$paypalGateway = new PayPalGateway ( $paypalConfig );
					$paypalGateway->setConfig ( $paypalConfig );
					
					$paypalGateway->cancelSubscription ( $profileId, "User Cancel the recurring payment" );
					
					$item->profileId = "";
					$item->status = PackageOrderEntity::CANCELLED;
					$this->dealOrderDataService->update ( $item );
					echo "Your request has been processed successfully. And the contract will be cancelled on the last day of the billing cycle";
					exit ();
				} catch ( Exception $ex ) {
					//echo $ex->getMessage();
					//die();
					echo "Your request has been failed. Please try again or contact to our administrator for supporting.";
					exit ();
				}
			
			}
			echo "Your request has already been cancelled.";
			exit ();
		} else if ($paymentMethod == PAYMENT_2CHECKOUT) {
		
		}
		echo "Your request has been failed. Please try again or contact to our administrator for supporting.";
		exit ();
	}
}
